package com.example.administrator.base.activity;


import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.CoordinateConverter;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.Circle;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.MultiPointItem;
import com.amap.api.maps.model.MultiPointOverlay;
import com.amap.api.maps.model.MultiPointOverlayOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polygon;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.cncoderx.wheelview.OnWheelChangedListener;
import com.cncoderx.wheelview.Wheel3DView;
import com.cncoderx.wheelview.WheelView;
import com.example.administrator.base.R;
import com.example.administrator.base.bean.AreaBunds;
import com.example.administrator.base.bean.BicycleInfo;
import com.example.administrator.base.bean.CityBunds;
import com.example.administrator.base.bean.CityList;
import com.example.administrator.base.bean.ReLogout;
import com.example.administrator.base.bean.SingleBicycle;
import com.example.administrator.base.bean.StationInfo;
import com.example.administrator.base.fragment.MineFragment;
import com.example.administrator.base.fragment.SetFragment;
import com.example.administrator.base.service.UploadLocation;
import com.example.administrator.base.util.AppManager;
import com.example.administrator.base.util.ChangeLatToLon;
import com.example.administrator.base.util.GPSUtil;
import com.example.administrator.base.util.GsonTools;
import com.example.administrator.base.util.NoToName;
import com.example.administrator.base.util.SharedPreferencesUtils;
import com.example.zhouwei.library.CustomPopWindow;
import com.github.lguipeng.library.animcheckbox.AnimCheckBox;
import com.github.rubensousa.floatingtoolbar.FloatingToolbar;
import com.ysyao.bottomtabbar.OnSelectableTextViewClickedListener;
import com.ysyao.bottomtabbar.SelectableBottomTextView;

import java.io.File;
import java.io.IOException;
import java.security.AlgorithmConstraints;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class MainActivity extends Activity implements AnimCheckBox.OnCheckedChangeListener {
    @InjectView(R.id.bus)
    SelectableBottomTextView bus;
    @InjectView(R.id.bag)
    SelectableBottomTextView bag;
    @InjectView(R.id.tourism)
    SelectableBottomTextView tourism;
    @InjectView(R.id.floatingToolbar)
    FloatingToolbar floatingToolbar;
    @InjectView(R.id.fab)
    FloatingActionButton fab;
    @InjectView(R.id.activity_main2)
    RelativeLayout activityMain2;
    @InjectView(R.id.ib_location)
    ImageButton ibLocation;
    @InjectView(R.id.car_number)
    TextView carNumber;
    @InjectView(R.id.location_number)
    TextView locationNumber;
    @InjectView(R.id.sr_search)
    SearchView srSearch;
    @InjectView(R.id.listView)
    ListView listView;
    @InjectView(R.id.map)
    MapView map;
    @InjectView(R.id.wheel)
    Wheel3DView wheel;
    @InjectView(R.id.tv_city)
    TextView tvCity;
    @InjectView(R.id.ll_wheel)
    LinearLayout llWheel;

    RelativeLayout rl_choose, rl_low, rl_break, rl_zombie, rl_back;
    private SetFragment setFragment;
    private MineFragment mineFragment;
    private MultiPointOverlay multiPointOverlay0, multiPointOverlay1, multiPointOverlay2, multiPointOverlay3, multiPointOverlay4, multiPointOverlay5, multiPointOverlay6, multiPointOverlay7,
            multiPointOverlay8, multiPointOverlay9, multiPointOverlay10, multiPointOverlay11, multiPointOverlay12, multiPointOverlay13,
            multiPointOverlay14, multiPointOverlay15, multiPointOverlay16,multiPointOverlay17,multiPointOverlay18,multiPointOverlay19;

    private MultiPointOverlayOptions overlayOptions0, overlayOptions1, overlayOptions2, overlayOptions3, overlayOptions4, overlayOptions5, overlayOptions6, overlayOptions7, overlayOptions8,
            overlayOptions9, overlayOptions10, overlayOptions11, overlayOptions12, overlayOptions13, overlayOptions14, overlayOptions15, overlayOptions16,overlayOptions17,overlayOptions18,overlayOptions19;

    private List<MultiPointItem> list0, list1, list2, list3, list4, list5, list6, list7, list8, list9, list10, list11, list12, list13, list14, list15, list16,list17,list18,list19;


    private String Url = "http://yingyan.baidu.com/api/v3/entity/aroundsearch";
    private String PolUrl = "http://yingyan.baidu.com/api/v3/entity/polygonsearch";
    CustomPopWindow popWindow, markerWindow;
    View contentView, inforwindowView, inforwindowViewstation;
    Button btnNavi;
    AnimCheckBox checkBox1, checkBox2, checkBox3, checkBox4, checkBox5, checkBox6, checkBox7, checkBox8,
            checkBox9, checkBox10, checkBox11, checkBox12, checkBox13, checkBox14, checkBox15, checkBox16,
            checkBox17,checkBox18,checkBox19,checkBox20;
    TextView carnumber, cartype, cityno, stationname, cityname, statintype, isline;
    EditText daynumber, nightnumber;
    Button uploadnumber, btndelete;
    double Location_latitude = 0.0, Location_Longitude = 0.0;
    private boolean isExit = false;
    SweetAlertDialog sweetAlertDialog;
    String markerId = "";
    List<LatLng> latLngs;
    List<LatLng> xiaoquyulatLngs;
    Toast toast;
    List<String> mStrings;
    ArrayAdapter<String> adapter;
    String city = "";
    int car0 = 0, car1 = 0, car2 = 0, car3 = 0, car4 = 0, car5 = 0, car6 = 0, car7 = 0, car8 = 0, car9 = 0,
            car10 = 0, car11 = 0, car12 = 0, car13 = 0, car14 = 0, car15 = 0, car16 = 0,car17,car18,car19, carall = 0, pointall = 0;

    public AMapLocationClient mLocationClient = null;
    public AMapLocationListener mLocationListener;
    public AMapLocationClientOption mLocationOption = null;
    public CoordinateConverter converter;
    String newpointlist = "";
    String pointlist = "";
    private boolean isFirst = true;
    int time = 0;
    int page = 0;
    int timep = 0;
    int pagep = 0;
    private boolean isDestroy = false;
    private PoiSearch.Query searchq;
    private PoiSearch poiSearch;
    List<PoiItem> result;
    private String isAreaOverLay = "1";
    private int xzqId;
    private int xqyId;
    Polygon yuanshipolygon, polygon;//小区域边框
    List<CityList.DeliverCityBean> deliverCity;//城市
    List<CityBunds.FencesBean.CfencesBean> cfences;//行政区
    List<CityBunds.FencesBean.CfencesBean.DfencesBean> dfences;//小区域
    List<AreaBunds.FencesBean.DfencesBean> dfencesBeen;//小区域
    private int AreaId = 0;
    String markerLat, markerLon;
    Circle circle;
    double ciclat, ciclon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main2);
        ButterKnife.inject(this);
        map.onCreate(savedInstanceState);
        AppManager.getAppManager().addActivity(this);
        init();
        getCityName();
        mLocationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation amapLocation) {
                if (amapLocation != null) {
                    if (amapLocation.getErrorCode() == 0) {
                        double[] bd09 = GPSUtil.gcj02_To_Bd09(amapLocation.getLatitude(), amapLocation.getLongitude());
                        double latitude = bd09[0];
                        double longitude = bd09[1];
                        Location_latitude = amapLocation.getLatitude();
                        Location_Longitude = amapLocation.getLongitude();
                        String latx = String.valueOf(latitude);
                        String lonx = String.valueOf(longitude);
                        SharedPreferencesUtils.setParam(MainActivity.this, "latitude", latx);
                        SharedPreferencesUtils.setParam(MainActivity.this, "longtitude", lonx);
                        if (amapLocation.getAddress() == null) {
                            SharedPreferencesUtils.setParam(MainActivity.this, "changelocklocation", "获取地址失败");
                        } else {
                            String changelocklocation = amapLocation.getAddress();
                            Log.i("gaodemap", changelocklocation);
                            SharedPreferencesUtils.setParam(MainActivity.this, "changelocklocation", changelocklocation);
                        }
                        if (amapLocation.getLocationDetail() == null) {
                            SharedPreferencesUtils.setParam(MainActivity.this, "address", "获取地址失败");
                        } else {
                            SharedPreferencesUtils.setParam(MainActivity.this, "address", amapLocation.getAddress());
                            Log.i("gaodemap", amapLocation.getAddress());
                        }
                        if (amapLocation.getProvince() == null) {

                            SharedPreferencesUtils.setParam(MainActivity.this, "city", "上海");
                        } else {
                            SharedPreferencesUtils.setParam(MainActivity.this, "city", amapLocation.getProvince());
                            city = amapLocation.getProvince();
                        }
                        SharedPreferencesUtils.setParam(MainActivity.this, "location3378", "" + amapLocation.getProvince() + "," + amapLocation.getDistrict());
                        if (isFirst) {
                            ciclat = Location_latitude;
                            ciclon = Location_Longitude;
                            resetLocation(Location_latitude, Location_Longitude, 19);
                            sweetAlertDialog.show();
                            IsOverArea(Location_latitude, Location_Longitude);
                            IsOverAreaPoint(Location_latitude, Location_Longitude);
                            startService(new Intent(MainActivity.this, UploadLocation.class));
                            isFirst = false;
                        }
                    } else {
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        Log.e("AmapError", "location Error, ErrCode:"
                                + amapLocation.getErrorCode() + ", errInfo:"
                                + amapLocation.getErrorInfo());
                    }
                }
            }
        };
        initLocation();
      /*  isGetAraeBunds();*/
        bus.setOnTextViewClickedListener(new OnSelectableTextViewClickedListener() {
            @Override
            public void onTextViewClicked(View v) {
                FragmentManager fm = getFragmentManager();
                FragmentTransaction transaction = fm.beginTransaction();
                transaction.remove(setFragment);
                transaction.remove(mineFragment);
                transaction.commit();
            }
        });


        bag.setOnTextViewClickedListener(new OnSelectableTextViewClickedListener() {
            @Override
            public void onTextViewClicked(View v) {
                FragmentManager fm = getFragmentManager();
                FragmentTransaction transaction = fm.beginTransaction();
                transaction.replace(R.id.replace, mineFragment);
                transaction.commit();

            }
        });
        tourism.setOnTextViewClickedListener(new OnSelectableTextViewClickedListener() {
            @Override
            public void onTextViewClicked(View v) {
                FragmentManager fm = getFragmentManager();
                FragmentTransaction transaction = fm.beginTransaction();
                transaction.replace(R.id.replace, setFragment);
                transaction.commit();
            }
        });

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                floatingToolbar.show();

            }
        });


        rl_choose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                floatingToolbar.hide();
                int px = dip2px(MainActivity.this, 20);
                popWindow = new CustomPopWindow.PopupWindowBuilder(MainActivity.this)
                        .setView(contentView)
                        .setFocusable(true)
                        .setOutsideTouchable(true)
                        .setAnimationStyle(R.style.CustomPopWindowStyle)
                        .create()
                        .showAsDropDown(srSearch, -px, 0);


            }
        });
        rl_low.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                floatingToolbar.hide();
                Intent intent = new Intent(MainActivity.this, SerchCar.class);
                intent.putExtra("type", "low");
                startActivity(intent);

            }
        });
        rl_zombie.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                floatingToolbar.hide();
                Intent intent = new Intent(MainActivity.this, SerchCar.class);
                intent.putExtra("type", "zombie");
                startActivity(intent);

            }
        });
        rl_break.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                floatingToolbar.hide();
                Intent intent = new Intent(MainActivity.this, SerchCar.class);
                intent.putExtra("type", "break");
                startActivity(intent);

            }
        });

        rl_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                floatingToolbar.hide();

            }
        });

        srSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if (city.equals("")) {
                    Toast.makeText(MainActivity.this, "获取城市地址失败，请重试", Toast.LENGTH_LONG).show();
                } else {
                    searchq = new PoiSearch.Query(query, "", city);
                    searchq.setPageSize(10);// 设置每页最多返回多少条poiitem
                    searchq.setPageNum(1);//设置查询页码
                    poiSearch = new PoiSearch(MainActivity.this, searchq);
                    poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
                        @Override
                        public void onPoiSearched(PoiResult poiResult, int i) {
                            mStrings.clear();
                            if (poiResult.getPois() == null) {
                                Toast.makeText(MainActivity.this, "未找到相关地址", Toast.LENGTH_LONG);
                            } else {
                                result = poiResult.getPois();
                                int size = result.size();
                                for (int y = 0; y < size; y++) {
                                    String district = result.get(y).getTitle();
                                    mStrings.add(district);
                                }
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        listView.setVisibility(View.VISIBLE);
                                        adapter.notifyDataSetChanged();
                                    }
                                });

                            }

                        }

                        @Override
                        public void onPoiItemSearched(PoiItem poiItem, int i) {

                        }
                    });
                    poiSearch.searchPOIAsyn();
                }
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {

                return false;
            }
        });

        srSearch.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                mStrings.clear();
                listView.setVisibility(View.GONE);
                return false;
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (result != null) {
                    resetLocation(result.get(position).getLatLonPoint().getLatitude(), result.get(position).getLatLonPoint().getLongitude(), 19);
                } else {
                    Toast.makeText(MainActivity.this, "请输入完整地址", Toast.LENGTH_LONG).show();
                }
            }
        });

        //选择城市小区域
        wheel.setOnWheelChangedListener(new OnWheelChangedListener() {
            @Override
            public void onChanged(WheelView view, int oldIndex, int newIndex) {
                vibrate();
                String text = (String) wheel.getItem(newIndex);
                switch (isAreaOverLay) {
                    case "1":
                        tvCity.setText(text);
                        AreaId = deliverCity.get(newIndex).getCityAreaId();
                        break;
                    case "2":
                        tvCity.setText(text);
                        xzqId = newIndex;
                        break;
                    case "3":
                        tvCity.setText(text);
                        xqyId = newIndex;
                        break;
                    default:
                        break;
                }
            }
        });

        uploadnumber.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (nightnumber.getText().toString().equals("")) {
                    if (daynumber.getText().toString().equals("")) {
                        Toast.makeText(MainActivity.this, "请输入数量", Toast.LENGTH_LONG).show();
                    } else {
                        sweetAlertDialog.show();
                        String type = "0";
                        String number = daynumber.getText().toString();
                        uploadNumber(markerId, number, type);
                    }
                } else {
                    if (daynumber.getText().toString().equals("")) {
                        sweetAlertDialog.show();
                        String type = "1";
                        String number = nightnumber.getText().toString();
                        uploadNumber(markerId, number, type);
                    } else {
                        Toast.makeText(MainActivity.this, "请勿同时输入", Toast.LENGTH_LONG).show();
                    }
                }
            }
        });

        btndelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SweetAlertDialog sweetAlertDialog = new SweetAlertDialog(MainActivity.this, SweetAlertDialog.WARNING_TYPE);
                sweetAlertDialog.setCanceledOnTouchOutside(true);
                sweetAlertDialog
                        .setTitleText("确定要删除吗?")
                        .setContentText("删除后点位将永久消失！")
                        .setConfirmText("是的，我要删除")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sDialog) {
                                markerWindow.dissmiss();
                                deletePoint(markerId, sDialog);

                            }
                        })

                        .show();
            }
        });
        /*导航*/
        btnNavi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startGaoDeMap(markerLat, markerLon, "0");
            }
        });

//海量点点击事件
        getMap().setOnMultiPointClickListener(new AMap.OnMultiPointClickListener() {
            @Override
            public boolean onPointClick(MultiPointItem multiPointItem) {
                Object object = multiPointItem.getObject();
                if (object instanceof SingleBicycle.EntitiesBean) {
                    SingleBicycle.EntitiesBean entitiesBean = (SingleBicycle.EntitiesBean) object;
                    markerLat = String.valueOf(entitiesBean.getLatest_location().getLatitude());
                    markerLon = String.valueOf(entitiesBean.getLatest_location().getLongitude());
                    resetLocation(entitiesBean.getLatest_location().getLatitude(), entitiesBean.getLatest_location().getLongitude(), 19);
                    carnumber.setText(getString(R.string.empty, entitiesBean.getEntity_name()));
                    String name = NoToName.numberToName(MainActivity.this, Integer.parseInt(entitiesBean.getCityNo()));
                    cityno.setText(name);
                    if (entitiesBean.getStatus() != null) {
                        switch (entitiesBean.getStatus()) {
                         /*（0：正常 1：使用中  2:离线 3:报废 4:升级 5：预约中 6:借车处理中 7：故障    8：低电量车 ）*/
                            case "0":
                                cartype.setText("正常车");
                                break;
                            case "1":
                                cartype.setText("使用中");
                                break;
                            case "2":
                                cartype.setText("离线");
                                break;
                            case "3":
                                cartype.setText("报废");
                                break;
                            case "4":
                                cartype.setText("升级");
                                break;
                            case "5":
                                cartype.setText("预约中");
                                break;
                            case "6":
                                cartype.setText("借车处理中");
                                break;
                            case "7":
                                cartype.setText("故障");
                                break;
                            case "8":
                                cartype.setText("低电量车");
                                break;
                            case "9":
                                cartype.setText("僵尸车");
                                break;
                            case "10":
                                cartype.setText("不可充电车");
                                break;
                            case "11":
                                cartype.setText("维修中");
                                break;
                            case "12":
                                cartype.setText("未绑定");
                                break;
                            case "13":
                                cartype.setText("电子围栏外");
                                break;
                            case "14":
                                cartype.setText("用户报故障车");
                                break;
                            case "15":
                                cartype.setText("需召回车辆");
                                break;
                            case "16":
                                cartype.setText("关机车");
                                break;
                            default:
                        }
                    }
                    markerWindow = new CustomPopWindow.PopupWindowBuilder(MainActivity.this)
                            .setView(inforwindowView)
                            .setFocusable(true)
                            .setOutsideTouchable(true)
                            .setAnimationStyle(R.style.CustomPopWindowStyle)
                            .create()
                            .showAtLocation(map, Gravity.BOTTOM, 0, bag.getHeight() + 10);
                } else {
                    StationInfo.EntitiesBean stationExInfo = (StationInfo.EntitiesBean) object;
                    markerId = stationExInfo.getEntity_name();
                    resetLocation(stationExInfo.getLatest_location().getLatitude(), stationExInfo.getLatest_location().getLongitude(), 19);
                    String[] number = stationExInfo.getPeakParkingNum().split("\\|");
                    stationname.setText(getString(R.string.empty, stationExInfo.getPointName()));
                    cityname.setText(getString(R.string.empty, stationExInfo.getChildrenAreaId()));
                    if (stationExInfo.getLatest_location().getLineFlag() != null) {
                        if (stationExInfo.getLatest_location().getLineFlag().equals("1")) {
                            isline.setText("有");
                        } else {
                            isline.setText("无");
                        }
                    }
                    daynumber.setText("");
                    nightnumber.setText("");
                    String day_number = number[0];
                    String night_number = number[1];
                    daynumber.setHint("" + day_number);
                    nightnumber.setHint("" + night_number);
                    String type = stationExInfo.getChildrenAreaType();
                    if (type != null) {
                        switch (type) {
                            case "1":
                                statintype.setText("预投放点");
                                break;
                            case "5":
                                statintype.setText("已投放点");
                                break;
                            case "4":
                                statintype.setText("重点投放点");
                                break;
                            case "3":
                                statintype.setText("一期投放点");
                                break;
                            case "6":
                                statintype.setText("临时维修点");
                                break;
                            case "7":
                                statintype.setText("临时集中点");
                                break;
                            default:
                                break;
                        }
                    }
                    markerWindow = new CustomPopWindow.PopupWindowBuilder(MainActivity.this)
                            .setView(inforwindowViewstation)
                            .setFocusable(true)
                            .setOutsideTouchable(true)
                            .setAnimationStyle(R.style.CustomPopWindowStyle)
                            .create()
                            .showAtLocation(map, Gravity.BOTTOM, 0, bag.getHeight() + 10);
                }
                return false;
            }
        });

        getMap().setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {

            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                ciclat = cameraPosition.target.latitude;
                ciclon = cameraPosition.target.longitude;
                if (circle != null) {
                    circle.remove();
                    setClc(ciclat, ciclon);
                } else {
                    setClc(ciclat, ciclon);
                }
            }
        });

    }

    @OnClick({R.id.btn_cancel, R.id.btn_done, R.id.ib_location, R.id.ib_reload})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_cancel:
                llWheel.setVisibility(View.GONE);
                break;
            case R.id.btn_done:
                switch (isAreaOverLay) {
                    case "1":
                        sweetAlertDialog.show();
                        isAreaOverLay = "2";
                        getAreaBands(String.valueOf(AreaId), "2");
                        break;
                    case "2":
                        sweetAlertDialog.show();
                        isAreaOverLay = "3";
                        int size = cfences.get(xzqId).getDfences().size();
                        dfences = cfences.get(xzqId).getDfences();
                        final String[] cityname = new String[size];
                        for (int i = 0; i < size; i++) {
                            String cityName = dfences.get(i).getAreaName();
                            cityname[i] = cityName;
                        }
                        Toast.makeText(MainActivity.this, "请选择要查看的小区域", Toast.LENGTH_LONG).show();
                        wheel.setEntries(cityname);
                        tvCity.setText(wheel.getItem(0));
                        llWheel.setVisibility(View.VISIBLE);
                        sweetAlertDialog.dismiss();
                        break;
                    case "3":
                        yuanshipolygon.remove();
                        sweetAlertDialog.show();
                        xiaoquyulatLngs.clear();
                        llWheel.setVisibility(View.GONE);
                        if (dfences != null) {
                            String fence = dfences.get(xqyId).getFence();
                            if (!fence.equals("")) {
                                Log.i("221152121", fence);
                                String[] point1 = fence.split("\\||,");
                                int y = point1.length;
                                for (int i = 0; i < y; i += 2) {
                                    LatLng latLng = new LatLng(Double.parseDouble(point1[i + 1]), Double.parseDouble(point1[i]));
                                    converter.coord(latLng);
                                    LatLng desLatLng = converter.convert();
                                    xiaoquyulatLngs.add(desLatLng);
                                }
                                if (xiaoquyulatLngs.isEmpty()) {
                                    Toast.makeText(MainActivity.this, "小区域有误，请重试", Toast.LENGTH_LONG).show();
                                    return;
                                }
                                PolygonOptions polygonOptions = new PolygonOptions();
                                polygonOptions.addAll(xiaoquyulatLngs);
                                polygonOptions.strokeWidth(15)
                                        .strokeColor(Color.argb(200, 250, 20, 60))
                                        .fillColor(Color.argb(0, 0, 0, 0));   // 多边形的填充色
                                polygon = getMap().addPolygon(polygonOptions);
                                resetnewLocation(xiaoquyulatLngs);
                                String[] split = fence.split("\\|");
                                pointlist = "";
                                newpointlist = "";
                                for (String aSplit : split) {
                                    String latLon = ChangeLatToLon.LatLon(aSplit);
                                    pointlist = pointlist + latLon + ";";
                                }
                                newpointlist = pointlist.substring(0, pointlist.length() - 1);
                                Log.i("15215445", newpointlist);
                                if (AreaId == 0) {
                                    String cityNo = String.valueOf(SharedPreferencesUtils.getParam(MainActivity.this, "cityNo", ""));
                                    Log.i("2121151", cityNo);
                                   /* IsOverArea(newpointlist, cityNo);*/
                                    /*IsOverAreaPoint(newpointlist);*/
                                } else {
                                    Log.i("2121151", "xxx" + AreaId);
                                  /*  IsOverArea(newpointlist, String.valueOf(AreaId));*/
                                   /* IsOverAreaPoint(newpointlist);*/
                                }
                            } else {
                                Toast.makeText(MainActivity.this, "该小区域未绘制边界", Toast.LENGTH_LONG).show();
                            }
                        } else {
                            String fence = dfencesBeen.get(xqyId).getFence();
                            if (!fence.equals("")) {
                                Log.i("221152121", fence);
                                String[] point1 = fence.split("\\||,");
                                int y = point1.length;
                                for (int i = 0; i < y; i += 2) {
                                    LatLng latLng = new LatLng(Double.parseDouble(point1[i + 1]), Double.parseDouble(point1[i]));
                                    converter.coord(latLng);
                                    LatLng desLatLng = converter.convert();
                                    xiaoquyulatLngs.add(desLatLng);
                                }
                                if (xiaoquyulatLngs.isEmpty()) {
                                    Toast.makeText(MainActivity.this, "小区域有误，请重试", Toast.LENGTH_LONG).show();
                                    return;
                                }
                                PolygonOptions polygonOptions = new PolygonOptions();
                                polygonOptions.addAll(xiaoquyulatLngs);
                                polygonOptions.strokeWidth(15)
                                        .strokeColor(Color.argb(200, 250, 20, 60))
                                        .fillColor(Color.argb(0, 0, 0, 0));   // 多边形的填充色
                                polygon = getMap().addPolygon(polygonOptions);
                                resetnewLocation(xiaoquyulatLngs);
                                String[] split = fence.split("\\|");
                                pointlist = "";
                                newpointlist = "";
                                for (String aSplit : split) {
                                    String latLon = ChangeLatToLon.LatLon(aSplit);
                                    pointlist = pointlist + latLon + ";";
                                }
                                newpointlist = pointlist.substring(0, pointlist.length() - 1);
                                Log.i("15215445", newpointlist);
                                if (AreaId == 0) {
                                    String cityNo = String.valueOf(SharedPreferencesUtils.getParam(MainActivity.this, "cityNo", ""));
                                    Log.i("2121151", cityNo);
                                   /* IsOverArea(newpointlist, cityNo);*/
                                   /* IsOverAreaPoint(newpointlist);*/
                                } else {
                                    Log.i("2121151", "xxx" + AreaId);
                                   /* IsOverArea(newpointlist, String.valueOf(AreaId));*/
                                   /* IsOverAreaPoint(newpointlist);*/
                                }
                            } else {
                                Toast.makeText(MainActivity.this, "该小区域未绘制边界", Toast.LENGTH_LONG).show();
                            }
                        }
                        break;
                    case "4":
                        break;
                    default:
                        break;
                }


                break;
            case R.id.ib_location:
                resetLocation(Location_latitude, Location_Longitude, 20);
                break;
            case R.id.ib_reload:
                reloadMap();
                if (PtInPolygon(new LatLng(ciclat, ciclon), latLngs)) {
                    sweetAlertDialog.show();
                    IsOverArea(ciclat, ciclon);
                    IsOverAreaPoint(ciclat, ciclon);
                } else {
                    Toast.makeText(MainActivity.this, "请移动到所属区域查看", Toast.LENGTH_LONG).show();
                }
               /* isGetAraeBunds();*/
                break;
        }
    }

    public void reloadMap() {
        mapClear();
        setClc(ciclat, ciclon);
        setPolygon();
    }

    public void mapClear() {
        carNumber.setText("");
        locationNumber.setText("");
        car0 = 0;
        car1 = 0;
        car2 = 0;
        car3 = 0;
        car4 = 0;
        car5 = 0;
        car6 = 0;
        car7 = 0;
        car8 = 0;
        car9 = 0;
        car10 = 0;
        car11 = 0;
        car12 = 0;
        car13 = 0;
        car14 = 0;
        car15 = 0;
        car16 = 0;
        car17 = 0;
        car18 = 0;
        car19 = 0;
        carall = 0;
        pointall = 0;
        getMap().clear();
        multiPointOverlay0 = getMap().addMultiPointOverlay(overlayOptions0);
        multiPointOverlay1 = getMap().addMultiPointOverlay(overlayOptions1);
        multiPointOverlay2 = getMap().addMultiPointOverlay(overlayOptions2);
        multiPointOverlay3 = getMap().addMultiPointOverlay(overlayOptions3);
        multiPointOverlay4 = getMap().addMultiPointOverlay(overlayOptions4);
        multiPointOverlay5 = getMap().addMultiPointOverlay(overlayOptions5);
        multiPointOverlay6 = getMap().addMultiPointOverlay(overlayOptions6);
        multiPointOverlay7 = getMap().addMultiPointOverlay(overlayOptions7);
        multiPointOverlay8 = getMap().addMultiPointOverlay(overlayOptions8);
        multiPointOverlay9 = getMap().addMultiPointOverlay(overlayOptions9);
        multiPointOverlay10 = getMap().addMultiPointOverlay(overlayOptions10);
        multiPointOverlay11 = getMap().addMultiPointOverlay(overlayOptions11);
        multiPointOverlay12 = getMap().addMultiPointOverlay(overlayOptions12);
        multiPointOverlay13 = getMap().addMultiPointOverlay(overlayOptions13);
        multiPointOverlay14 = getMap().addMultiPointOverlay(overlayOptions14);
        multiPointOverlay15 = getMap().addMultiPointOverlay(overlayOptions15);
        multiPointOverlay16 = getMap().addMultiPointOverlay(overlayOptions16);
        multiPointOverlay17 = getMap().addMultiPointOverlay(overlayOptions17);
        multiPointOverlay18 = getMap().addMultiPointOverlay(overlayOptions18);
        multiPointOverlay19 = getMap().addMultiPointOverlay(overlayOptions19);
    }

    public void init() {
        sweetAlertDialog = new SweetAlertDialog(this, 5);
        sweetAlertDialog.setTitleText("加载中");
        result = new ArrayList<>();
        converter = new CoordinateConverter(this);
        UiSettings mUiSettings = getMap().getUiSettings();
        mUiSettings.setZoomControlsEnabled(false);
        mUiSettings.setRotateGesturesEnabled(false);
        mUiSettings.setLogoBottomMargin(-50);
        mUiSettings.setTiltGesturesEnabled(false);
        mStrings = new ArrayList<>();
        adapter = new ArrayAdapter<>(this, R.layout.layout, mStrings);
        listView.setAdapter(adapter);
        srSearch.setIconifiedByDefault(true);
        srSearch.setIconified(true);
        toast = Toast.makeText(MainActivity.this, "移到所属区域内，才可查看相关数据", Toast.LENGTH_SHORT);
        latLngs = new ArrayList<>();
        xiaoquyulatLngs = new ArrayList<>();
        mineFragment = new MineFragment();
        setFragment = new SetFragment();
        MyLocationStyle myLocationStyle;
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
        map.getMap().setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        map.getMap().setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        floatingToolbar.attachFab(fab);

        contentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.popwindow, null);
        inforwindowView = LayoutInflater.from(MainActivity.this).inflate(R.layout.inforwindow, null);
        inforwindowViewstation = LayoutInflater.from(MainActivity.this).inflate(R.layout.inforwindowstation, null);

        rl_choose = (RelativeLayout) floatingToolbar.getCustomView().findViewById(R.id.rl_choose);
        rl_low = (RelativeLayout) floatingToolbar.getCustomView().findViewById(R.id.rl_low);
        rl_break = (RelativeLayout) floatingToolbar.getCustomView().findViewById(R.id.rl_break);
        rl_back = (RelativeLayout) floatingToolbar.getCustomView().findViewById(R.id.rl_back);
        rl_zombie = (RelativeLayout) floatingToolbar.getCustomView().findViewById(R.id.rl_zombie);

        carnumber = (TextView) inforwindowView.findViewById(R.id.carnumber);
        cartype = (TextView) inforwindowView.findViewById(R.id.cartype);
        cityno = (TextView) inforwindowView.findViewById(R.id.citynumber);
        btnNavi = (Button) inforwindowView.findViewById(R.id.btn_navi);

        stationname = (TextView) inforwindowViewstation.findViewById(R.id.stationname);
        statintype = (TextView) inforwindowViewstation.findViewById(R.id.stationtype);
        cityname = (TextView) inforwindowViewstation.findViewById(R.id.cityname);
        isline = (TextView) inforwindowViewstation.findViewById(R.id.isline);

        daynumber = (EditText) inforwindowViewstation.findViewById(R.id.daynumber);
        nightnumber = (EditText) inforwindowViewstation.findViewById(R.id.nightnumber);

        uploadnumber = (Button) inforwindowViewstation.findViewById(R.id.uploadnumber);
        btndelete = (Button) inforwindowViewstation.findViewById(R.id.btn_delete);

        checkBox1 = (AnimCheckBox) contentView.findViewById(R.id.checkbox1);
        checkBox2 = (AnimCheckBox) contentView.findViewById(R.id.checkbox2);
        checkBox3 = (AnimCheckBox) contentView.findViewById(R.id.checkbox3);
        checkBox4 = (AnimCheckBox) contentView.findViewById(R.id.checkbox4);
        checkBox5 = (AnimCheckBox) contentView.findViewById(R.id.checkbox5);
        checkBox6 = (AnimCheckBox) contentView.findViewById(R.id.checkbox6);
        checkBox7 = (AnimCheckBox) contentView.findViewById(R.id.checkbox7);
        checkBox8 = (AnimCheckBox) contentView.findViewById(R.id.checkbox8);
        checkBox9 = (AnimCheckBox) contentView.findViewById(R.id.checkbox9);
        checkBox10 = (AnimCheckBox) contentView.findViewById(R.id.checkbox10);
        checkBox15 = (AnimCheckBox) contentView.findViewById(R.id.checkbox15);
        checkBox16 = (AnimCheckBox) contentView.findViewById(R.id.checkbox16);
        checkBox17 = (AnimCheckBox) contentView.findViewById(R.id.checkbox17);
        checkBox18 = (AnimCheckBox) contentView.findViewById(R.id.checkbox18);
        checkBox19 = (AnimCheckBox) contentView.findViewById(R.id.checkbox19);
        checkBox20 = (AnimCheckBox) contentView.findViewById(R.id.checkbox20);

        checkBox11 = (AnimCheckBox) contentView.findViewById(R.id.checkbox11);
        checkBox12 = (AnimCheckBox) contentView.findViewById(R.id.checkbox12);
        checkBox13 = (AnimCheckBox) contentView.findViewById(R.id.checkbox13);
        checkBox14 = (AnimCheckBox) contentView.findViewById(R.id.checkbox14);
 /*（0：正常 1：使用中  2:离线 3:报废 4:升级 5：预约中 6:借车处理中 7：故障    8：低电量车 ）*/
        BitmapDescriptor bicycleBitmap1 = BitmapDescriptorFactory.fromResource(R.drawable.o1);
        BitmapDescriptor bicycleBitmap2 = BitmapDescriptorFactory.fromResource(R.drawable.o3);
        BitmapDescriptor bicycleBitmap3 = BitmapDescriptorFactory.fromResource(R.drawable.o5);
        BitmapDescriptor bicycleBitmap4 = BitmapDescriptorFactory.fromResource(R.drawable.o8);
        BitmapDescriptor bicycleBitmap5 = BitmapDescriptorFactory.fromResource(R.drawable.o4);
        BitmapDescriptor bicycleBitmap6 = BitmapDescriptorFactory.fromResource(R.drawable.o2);
        BitmapDescriptor bicycleBitmap7 = BitmapDescriptorFactory.fromResource(R.drawable.o6);
        BitmapDescriptor bicycleBitmap8 = BitmapDescriptorFactory.fromResource(R.drawable.o7);
        BitmapDescriptor bicycleBitmap9 = BitmapDescriptorFactory.fromResource(R.drawable.o11);
        BitmapDescriptor bicycleBitmap10 = BitmapDescriptorFactory.fromResource(R.drawable.o12);
        BitmapDescriptor bicycleBitmap15 = BitmapDescriptorFactory.fromResource(R.drawable.o13);
        BitmapDescriptor bicycleBitmap16 = BitmapDescriptorFactory.fromResource(R.drawable.o14);
        BitmapDescriptor bicycleBitmap17 = BitmapDescriptorFactory.fromResource(R.drawable.o15);
        BitmapDescriptor bicycleBitmap18 = BitmapDescriptorFactory.fromResource(R.drawable.o18);

        BitmapDescriptor bicycleBitmap11 = BitmapDescriptorFactory.fromResource(R.drawable.ltt);
        BitmapDescriptor bicycleBitmap12 = BitmapDescriptorFactory.fromResource(R.drawable.lttb);
        BitmapDescriptor bicycleBitmap13 = BitmapDescriptorFactory.fromResource(R.drawable.lttg);
        BitmapDescriptor bicycleBitmap14 = BitmapDescriptorFactory.fromResource(R.drawable.lltb);
        BitmapDescriptor bicycleBitmap19 = BitmapDescriptorFactory.fromResource(R.drawable.o17);
        BitmapDescriptor bicycleBitmap20 = BitmapDescriptorFactory.fromResource(R.drawable.o16);

        overlayOptions0 = new MultiPointOverlayOptions();
        overlayOptions0.icon(bicycleBitmap1);
        overlayOptions0.anchor(0.5f, 0.5f);
        multiPointOverlay0 = getMap().addMultiPointOverlay(overlayOptions0);
        list0 = new ArrayList<>();


        overlayOptions1 = new MultiPointOverlayOptions();
        overlayOptions1.icon(bicycleBitmap2);
        overlayOptions1.anchor(0.5f, 0.5f);
        multiPointOverlay1 = getMap().addMultiPointOverlay(overlayOptions1);
        list1 = new ArrayList<>();

        overlayOptions2 = new MultiPointOverlayOptions();
        overlayOptions2.icon(bicycleBitmap3);
        overlayOptions2.anchor(0.5f, 0.5f);
        multiPointOverlay2 = getMap().addMultiPointOverlay(overlayOptions2);
        list2 = new ArrayList<>();

        overlayOptions3 = new MultiPointOverlayOptions();
        overlayOptions3.icon(bicycleBitmap4);
        overlayOptions3.anchor(0.5f, 0.5f);
        multiPointOverlay3 = getMap().addMultiPointOverlay(overlayOptions3);
        list3 = new ArrayList<>();

        overlayOptions4 = new MultiPointOverlayOptions();
        overlayOptions4.icon(bicycleBitmap5);
        overlayOptions4.anchor(0.5f, 0.5f);
        multiPointOverlay4 = getMap().addMultiPointOverlay(overlayOptions4);
        list4 = new ArrayList<>();

        overlayOptions5 = new MultiPointOverlayOptions();
        overlayOptions5.icon(bicycleBitmap6);
        overlayOptions5.anchor(0.5f, 0.5f);
        multiPointOverlay5 = getMap().addMultiPointOverlay(overlayOptions5);
        list5 = new ArrayList<>();

        overlayOptions6 = new MultiPointOverlayOptions();
        overlayOptions6.icon(bicycleBitmap7);
        overlayOptions6.anchor(0.5f, 0.5f);
        multiPointOverlay6 = getMap().addMultiPointOverlay(overlayOptions6);
        list6 = new ArrayList<>();

        overlayOptions7 = new MultiPointOverlayOptions();
        overlayOptions7.icon(bicycleBitmap8);
        overlayOptions7.anchor(0.5f, 0.5f);
        multiPointOverlay7 = getMap().addMultiPointOverlay(overlayOptions7);
        list7 = new ArrayList<>();

        overlayOptions8 = new MultiPointOverlayOptions();
        overlayOptions8.icon(bicycleBitmap9);
        overlayOptions8.anchor(0.5f, 0.5f);
        multiPointOverlay8 = getMap().addMultiPointOverlay(overlayOptions8);
        list8 = new ArrayList<>();

        overlayOptions9 = new MultiPointOverlayOptions();
        overlayOptions9.icon(bicycleBitmap10);
        overlayOptions9.anchor(0.5f, 0.5f);
        multiPointOverlay9 = getMap().addMultiPointOverlay(overlayOptions9);
        list9 = new ArrayList<>();

        overlayOptions10 = new MultiPointOverlayOptions();
        overlayOptions10.icon(bicycleBitmap11);
        overlayOptions10.anchor(0.5f, 0.5f);
        multiPointOverlay10 = getMap().addMultiPointOverlay(overlayOptions10);
        list10 = new ArrayList<>();

        overlayOptions11 = new MultiPointOverlayOptions();
        overlayOptions11.icon(bicycleBitmap12);
        overlayOptions11.anchor(0.5f, 0.5f);
        multiPointOverlay11 = getMap().addMultiPointOverlay(overlayOptions11);
        list11 = new ArrayList<>();

        overlayOptions12 = new MultiPointOverlayOptions();
        overlayOptions12.icon(bicycleBitmap13);
        overlayOptions12.anchor(0.5f, 0.5f);
        multiPointOverlay12 = getMap().addMultiPointOverlay(overlayOptions12);
        list12 = new ArrayList<>();

        overlayOptions13 = new MultiPointOverlayOptions();
        overlayOptions13.icon(bicycleBitmap14);
        overlayOptions13.anchor(0.5f, 0.5f);
        multiPointOverlay13 = getMap().addMultiPointOverlay(overlayOptions13);
        list13 = new ArrayList<>();

        overlayOptions14 = new MultiPointOverlayOptions();
        overlayOptions14.icon(bicycleBitmap15);
        overlayOptions14.anchor(0.5f, 0.5f);
        multiPointOverlay14 = getMap().addMultiPointOverlay(overlayOptions14);
        list14 = new ArrayList<>();

        overlayOptions15 = new MultiPointOverlayOptions();
        overlayOptions15.icon(bicycleBitmap16);
        overlayOptions15.anchor(0.5f, 0.5f);
        multiPointOverlay15 = getMap().addMultiPointOverlay(overlayOptions15);
        list15 = new ArrayList<>();

        overlayOptions16 = new MultiPointOverlayOptions();
        overlayOptions16.icon(bicycleBitmap17);
        overlayOptions16.anchor(0.5f, 0.5f);
        multiPointOverlay16 = getMap().addMultiPointOverlay(overlayOptions16);
        list16 = new ArrayList<>();

        overlayOptions17 = new MultiPointOverlayOptions();
        overlayOptions17.icon(bicycleBitmap18);
        overlayOptions17.anchor(0.5f, 0.5f);
        multiPointOverlay17 = getMap().addMultiPointOverlay(overlayOptions17);
        list17 = new ArrayList<>();

        overlayOptions18 = new MultiPointOverlayOptions();
        overlayOptions18.icon(bicycleBitmap19);
        overlayOptions18.anchor(0.5f, 0.5f);
        multiPointOverlay18 = getMap().addMultiPointOverlay(overlayOptions18);
        list18 = new ArrayList<>();

        overlayOptions19 = new MultiPointOverlayOptions();
        overlayOptions19.icon(bicycleBitmap20);
        overlayOptions19.anchor(0.5f, 0.5f);
        multiPointOverlay19 = getMap().addMultiPointOverlay(overlayOptions19);
        list19 = new ArrayList<>();

        checkBox1.setOnCheckedChangeListener(this);
        checkBox2.setOnCheckedChangeListener(this);
        checkBox3.setOnCheckedChangeListener(this);
        checkBox4.setOnCheckedChangeListener(this);
        checkBox5.setOnCheckedChangeListener(this);
        checkBox6.setOnCheckedChangeListener(this);
        checkBox7.setOnCheckedChangeListener(this);
        checkBox8.setOnCheckedChangeListener(this);
        checkBox9.setOnCheckedChangeListener(this);
        checkBox10.setOnCheckedChangeListener(this);
        checkBox11.setOnCheckedChangeListener(this);
        checkBox12.setOnCheckedChangeListener(this);
        checkBox13.setOnCheckedChangeListener(this);
        checkBox14.setOnCheckedChangeListener(this);
        checkBox15.setOnCheckedChangeListener(this);
        checkBox16.setOnCheckedChangeListener(this);
        checkBox17.setOnCheckedChangeListener(this);
        checkBox18.setOnCheckedChangeListener(this);
        checkBox19.setOnCheckedChangeListener(this);
        checkBox20.setOnCheckedChangeListener(this);

        String point = String.valueOf(SharedPreferencesUtils.getParam(MainActivity.this, "position", ""));
        converter.from(CoordinateConverter.CoordType.BAIDU);
        if (!point.equals("")) {
            String[] point1 = point.split("\\||,");
            int y = point1.length;
            for (int i = 0; i < y; i += 2) {
                LatLng latLng = new LatLng(Double.parseDouble(point1[i + 1]), Double.parseDouble(point1[i]));
                converter.coord(latLng);
                LatLng desLatLng = converter.convert();
                latLngs.add(desLatLng);
            }
            setPolygon();
            String[] split = point.split("\\|");
            for (String aSplit : split) {
                String latLon = ChangeLatToLon.LatLon(aSplit);
                pointlist = pointlist + latLon + ";";
            }
            newpointlist = pointlist.substring(0, pointlist.length() - 1);

        }
    }

    public static boolean PtInPolygon(LatLng point, List<LatLng> APoints) {
        int nCross = 0;
        for (int i = 0; i < APoints.size(); i++) {
            LatLng p1 = APoints.get(i);
            LatLng p2 = APoints.get((i + 1) % APoints.size());
            // 求解 y=p.y 与 p1p2 的交点
            if (p1.longitude == p2.longitude)      // p1p2 与 y=p0.y平行
                continue;
            if (point.longitude < Math.min(p1.longitude, p2.longitude))   // 交点在p1p2延长线上
                continue;
            if (point.longitude >= Math.max(p1.longitude, p2.longitude))   // 交点在p1p2延长线上
                continue;
            // 求交点的 X 坐标 --------------------------------------------------------------
            double x = (double) (point.longitude - p1.longitude) * (double) (p2.latitude - p1.latitude) / (double) (p2.longitude - p1.longitude) + p1.latitude;
            if (x > point.latitude)
                nCross++; // 只统计单边交点
        }
        // 单边交点为偶数，点在多边形之外 ---
        return (nCross % 2 == 1);
    }

    //判断不同账户
    public void isGetAraeBunds() {
        sweetAlertDialog = new SweetAlertDialog(this, 5);
        sweetAlertDialog.setTitleText("加载中");
        sweetAlertDialog.show();
        String isHaveChildrenArea = String.valueOf(SharedPreferencesUtils.getParam(MainActivity.this, "childrenAreaId", ""));
        if (isHaveChildrenArea.equals("0") || isHaveChildrenArea.length() != 32) {
            //没有小区域，弹出筛选框
            String areaId = String.valueOf(SharedPreferencesUtils.getParam(MainActivity.this, "areaId", ""));
            if (areaId.equals("1")) {
                //获取全国投放城市列表
                Log.i("121545", "1");
                isAreaOverLay = "1";
                getAreaBands("", "1");
            } else {
                String syscode = String.valueOf(SharedPreferencesUtils.getParam(MainActivity.this, "sysCode", ""));
                if (syscode.equals("5")) {
                    //获取城市下级行政区
                    Log.i("121545", "2");
                    isAreaOverLay = "2";
                    tvCity.setText("请选择行政区及小区域");
                    getAreaBands("", "2");
                } else {
                    //获取小区域
                    Log.i("121545", "3");
                    isAreaOverLay = "3";
                    tvCity.setText("请选择小区域");
                    getAreaBands("", "3");
                }
            }
        } else {
            //有小区域，开始直接获取小区域内数据
            isAreaOverLay = "4";
            setPolygon();
            String cityNo = String.valueOf(SharedPreferencesUtils.getParam(MainActivity.this, "cityNo", ""));
          /*  IsOverArea(newpointlist, cityNo);*/
           /* IsOverAreaPoint(newpointlist);*/
        }
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            Log.i("2151561", "" + list0.size());
            if (msg.what == 1) {
                //正常
                carall = 0;
                multiPointOverlay0.setItems(list0);
                car0 = list0.size();
                if (checkBox1.isChecked()) {
                    carall = carall + car0;
                    multiPointOverlay0.setEnable(true);
                } else {
                    multiPointOverlay0.setEnable(false);
                }
                //未绑定
                multiPointOverlay5.setItems(list5);
                car5 = list5.size();
                if (checkBox2.isChecked()) {
                    carall = carall + car5;
                    multiPointOverlay5.setEnable(true);
                } else {
                    multiPointOverlay5.setEnable(false);
                }
                //使用中
                multiPointOverlay1.setItems(list1);
                car1 = list1.size();
                if (checkBox3.isChecked()) {
                    carall = carall + car1;
                    multiPointOverlay1.setEnable(true);
                } else {
                    multiPointOverlay1.setEnable(false);
                }
                //维修中
                multiPointOverlay4.setItems(list4);
                car4 = list4.size();
                if (checkBox4.isChecked()) {
                    carall = carall + car4;
                    multiPointOverlay4.setEnable(true);
                } else {
                    multiPointOverlay4.setEnable(false);
                }
                //离线
                multiPointOverlay2.setItems(list2);
                car2 = list2.size();
                if (checkBox5.isChecked()) {
                    carall = carall + car2;
                    multiPointOverlay2.setEnable(true);
                } else {
                    car2 = 0;
                    multiPointOverlay2.setEnable(false);
                }
                //不可充电
                multiPointOverlay6.setItems(list6);
                car6 = list6.size();
                if (checkBox6.isChecked()) {
                    carall = carall + car6;
                    multiPointOverlay6.setEnable(true);
                } else {
                    multiPointOverlay6.setEnable(false);
                }
                //故障
                multiPointOverlay7.setItems(list7);
                car7 = list7.size();
                if (checkBox7.isChecked()) {
                    carall = carall + car7;
                    multiPointOverlay7.setEnable(true);
                } else {
                    multiPointOverlay7.setEnable(false);
                }
                //报废
                multiPointOverlay3.setItems(list3);
                car3 = list3.size();
                if (checkBox8.isChecked()) {
                    carall = carall + car3;
                    multiPointOverlay3.setEnable(true);
                } else {
                    multiPointOverlay3.setEnable(false);
                }
                //低电量
                multiPointOverlay8.setItems(list8);
                car8 = list8.size();
                if (checkBox9.isChecked()) {
                    carall = carall + car8;
                    multiPointOverlay8.setEnable(true);
                } else {
                    multiPointOverlay8.setEnable(false);
                }
                //僵尸车
                multiPointOverlay9.setItems(list9);
                car9 = list9.size();
                if (checkBox10.isChecked()) {
                    carall = carall + car9;
                    multiPointOverlay9.setEnable(true);
                } else {
                    multiPointOverlay9.setEnable(false);
                }
                //围栏外
                multiPointOverlay14.setItems(list14);
                car14 = list14.size();
                if (checkBox15.isChecked()) {
                    carall = carall + car14;
                    multiPointOverlay14.setEnable(true);
                } else {
                    multiPointOverlay14.setEnable(false);
                }
                //用户报障
                multiPointOverlay15.setItems(list15);
                car15 = list15.size();
                if (checkBox16.isChecked()) {
                    carall = carall + car15;
                    multiPointOverlay15.setEnable(true);
                } else {
                    multiPointOverlay15.setEnable(false);
                }
                //召回
                multiPointOverlay16.setItems(list16);
                car16 = list16.size();
                if (checkBox17.isChecked()) {
                    carall = carall + car16;
                    multiPointOverlay16.setEnable(true);
                } else {
                    multiPointOverlay16.setEnable(false);
                }
                //关机
                multiPointOverlay17.setItems(list17);
                car17 = list17.size();
                if (checkBox18.isChecked()) {
                    carall = carall + car17;
                    multiPointOverlay17.setEnable(true);
                } else {
                    multiPointOverlay17.setEnable(false);
                }
                String all = String.valueOf(carall);
                carNumber.setText(all);

                list0.clear();
                list1.clear();
                list2.clear();
                list3.clear();
                list4.clear();
                list5.clear();
                list6.clear();
                list7.clear();
                list8.clear();
                list9.clear();
                list14.clear();
                list15.clear();
                list16.clear();
                list17.clear();
                sweetAlertDialog.dismiss();
            } else if (msg.what == 2) {
                //预投放
                multiPointOverlay10.setItems(list10);
                car10 = list10.size();
                if (checkBox11.isChecked()) {
                    pointall = pointall + car10;
                    multiPointOverlay10.setEnable(true);
                } else {
                    multiPointOverlay10.setEnable(false);
                }
                //一期
                multiPointOverlay11.setItems(list11);
                car11 = list11.size();
                if (checkBox12.isChecked()) {
                    pointall = pointall + car11;
                    multiPointOverlay11.setEnable(true);
                } else {
                    multiPointOverlay11.setEnable(false);
                }
                //重点
                multiPointOverlay12.setItems(list12);
                car12 = list12.size();
                if (checkBox13.isChecked()) {
                    pointall = pointall + car12;
                    multiPointOverlay12.setEnable(true);
                } else {
                    multiPointOverlay12.setEnable(false);
                }
                //已投放
                multiPointOverlay13.setItems(list13);
                car13 = list13.size();
                if (checkBox14.isChecked()) {
                    pointall = pointall + car13;
                    multiPointOverlay13.setEnable(true);
                } else {
                    multiPointOverlay13.setEnable(false);
                }
                //临时维修点
                multiPointOverlay18.setItems(list18);
                car18 = list18.size();
                if (checkBox19.isChecked()) {
                    pointall = pointall + car18;
                    multiPointOverlay18.setEnable(true);
                } else {
                    multiPointOverlay18.setEnable(false);
                }
                //临时中转点
                multiPointOverlay19.setItems(list19);
                car19 = list19.size();
                if (checkBox20.isChecked()) {
                    pointall = pointall + car19;
                    multiPointOverlay19.setEnable(true);
                } else {
                    multiPointOverlay19.setEnable(false);
                }
                String all = String.valueOf(pointall);
                locationNumber.setText(all);

                list10.clear();
                list11.clear();
                list12.clear();
                list13.clear();
                list18.clear();
                list19.clear();
            }

        }
    };


    /*设置定位选项*/
    private void initLocation() {
        mLocationClient = new AMapLocationClient(getApplicationContext());
        mLocationClient.setLocationListener(mLocationListener);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setInterval(5000);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setLocationCacheEnable(false);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();

    }

    /*移动初始地图镜头*/
    private void resetLocation(double v1, double v2, float x) {
        LatLng latlon = new LatLng(v1, v2);
        getMap().animateCamera(CameraUpdateFactory.newLatLngZoom(latlon, x), 1000, null);

    }


    /*移动地图至显示边界*/
    private void resetnewLocation(List<LatLng> latLngs) {
        if (latLngs == null) {
            return;
        }
        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        for (LatLng latLng : latLngs) {
            builder.include(latLng);
        }
        map.getMap().animateCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 1), 1000, null);

    }

    /*获取城市以及包含的小区域*/
    public void getAreaBands(String areaId, final String bean) {
        final OkHttpClient client = new OkHttpClient();
        final RequestBody formBody = new FormBody.Builder()
                .add("action", "GETFENCES")
                .add("adminId", String.valueOf(SharedPreferencesUtils.getParam(MainActivity.this, "adminId", "")))
                .add("cityAreaIdx", areaId)
                .build();
        final Request request = new Request.Builder()
                .url("http://operate.99bicycle.com/OperateBicyclePro/administrator?")
                .post(formBody)
                .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Log.i("121555121", "" + string);
                        switch (bean) {
                            case "1":
                                final CityList citylist = GsonTools.changeGsonToBean(string, CityList.class);
                                if (citylist != null) {
                                    if (citylist.getCode() == 1) {
                                        deliverCity = citylist.getDeliverCity();
                                        if (deliverCity != null) {
                                            int size = citylist.getDeliverCity().size();
                                            final String[] cityname = new String[size];
                                            for (int i = 0; i < size; i++) {
                                                String cityName = citylist.getDeliverCity().get(i).getCityName();
                                                cityname[i] = cityName;
                                            }
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    Toast.makeText(MainActivity.this, "请选择要查看的城市", Toast.LENGTH_LONG).show();
                                                    wheel.setEntries(cityname);
                                                    tvCity.setText(wheel.getItem(0));
                                                    AreaId = citylist.getDeliverCity().get(0).getCityAreaId();
                                                    llWheel.setVisibility(View.VISIBLE);
                                                    sweetAlertDialog.dismiss();
                                                }
                                            });
                                        } else {
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    Toast.makeText(MainActivity.this, "账号有误，请重新设置", Toast.LENGTH_LONG).show();
                                                    sweetAlertDialog.dismiss();
                                                }
                                            });
                                        }
                                    } else {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(MainActivity.this, "" + citylist.getMessage(), Toast.LENGTH_LONG).show();
                                                sweetAlertDialog.dismiss();
                                            }
                                        });
                                    }
                                } else {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(MainActivity.this, "数据错误请重试", Toast.LENGTH_LONG).show();
                                            sweetAlertDialog.dismiss();
                                        }
                                    });
                                }
                                break;
                            case "2":
                                final CityBunds cityBunds = GsonTools.changeGsonToBean(string, CityBunds.class);
                                if (cityBunds != null) {
                                    if (cityBunds.getCode() == 1) {
                                        cfences = cityBunds.getFences().getCfences();
                                        if (cfences != null) {
                                            int size = cityBunds.getFences().getCfences().size();//城市
                                            final String[] cityname = new String[size];
                                            for (int i = 0; i < size; i++) {
                                                String cityName = cityBunds.getFences().getCfences().get(i).getDistrict();
                                                cityname[i] = cityName;
                                            }
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    Toast.makeText(MainActivity.this, "请选择要查看的行政区", Toast.LENGTH_LONG).show();
                                                    wheel.setEntries(cityname);
                                                    tvCity.setText(wheel.getItem(0));
                                                    xzqId = 0;
                                                    llWheel.setVisibility(View.VISIBLE);
                                                    sweetAlertDialog.dismiss();
                                                }
                                            });
                                        } else {
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    Toast.makeText(MainActivity.this, "账号有误，请重新设置", Toast.LENGTH_LONG).show();
                                                    sweetAlertDialog.dismiss();
                                                }
                                            });
                                        }
                                    } else {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(MainActivity.this, "" + cityBunds.getMessage(), Toast.LENGTH_LONG).show();
                                                sweetAlertDialog.dismiss();
                                            }
                                        });
                                    }
                                } else {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(MainActivity.this, "数据错误请重试", Toast.LENGTH_LONG).show();
                                            sweetAlertDialog.dismiss();
                                        }
                                    });
                                }
                                break;
                            case "3":
                                final AreaBunds areaBunds = GsonTools.changeGsonToBean(string, AreaBunds.class);
                                if (areaBunds != null) {
                                    if (areaBunds.getCode() == 1) {
                                        if (areaBunds.getFences() != null) {
                                            dfencesBeen = areaBunds.getFences().getDfences();
                                            if (dfencesBeen != null) {
                                                int size = areaBunds.getFences().getDfences().size();
                                                final String[] cityname = new String[size];
                                                for (int i = 0; i < size; i++) {
                                                    String cityName = areaBunds.getFences().getDfences().get(i).getAreaName();
                                                    cityname[i] = cityName;
                                                }

                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        Toast.makeText(MainActivity.this, "请选择要查看的小区域", Toast.LENGTH_LONG).show();
                                                        wheel.setEntries(cityname);
                                                        tvCity.setText(wheel.getItem(0));
                                                        xqyId = 0;
                                                        llWheel.setVisibility(View.VISIBLE);
                                                        sweetAlertDialog.dismiss();
                                                    }
                                                });
                                            } else {
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        Toast.makeText(MainActivity.this, "账号有误，请重新设置", Toast.LENGTH_LONG).show();
                                                        sweetAlertDialog.dismiss();
                                                    }
                                                });
                                            }
                                        } else {
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    Toast.makeText(MainActivity.this, "账号有误，请重新设置", Toast.LENGTH_LONG).show();
                                                    sweetAlertDialog.dismiss();
                                                }
                                            });
                                        }
                                    } else {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(MainActivity.this, "" + areaBunds.getMessage(), Toast.LENGTH_LONG).show();
                                                sweetAlertDialog.dismiss();
                                            }
                                        });
                                    }
                                } else {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(MainActivity.this, "数据错误请重试", Toast.LENGTH_LONG).show();
                                            sweetAlertDialog.dismiss();
                                        }
                                    });
                                }
                                break;
                            default:
                                break;

                        }
                    } else {
                        throw new IOException("Unexpected code " + response);
                    }
                } catch (IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "网络异常请重试", Toast.LENGTH_LONG).show();
                            sweetAlertDialog.dismiss();
                        }
                    });
                    e.printStackTrace();
                }
            }
        }).start();

    }

    protected AMap getMap() {
        return map.getMap();
    }

    /*获取500米内所有车辆*/
    public void IsOverArea(final double v1, final double v2) {
        time = 0;
        String x = "" + v1 + "," + v2;
        OkHttpClient mOkHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(Url + "?ak=IK5AlGXoZ23tDAGjldRalicbhdpsrKwE&service_id=135958&center=" + x + "&radius=500&page_size=1&coord_type_input=gcj02")
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        sweetAlertDialog.dismiss();
                        Toast.makeText(MainActivity.this, "网络异常，请检查网络连接", Toast.LENGTH_LONG).show();
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String resp = response.body().string();
                Log.i("15641512", resp);
                final SingleBicycle singleBicycle = GsonTools.changeGsonToBean(resp, SingleBicycle.class);
                if (singleBicycle != null) {
                    if (singleBicycle.getStatus() == 0) {
                        double total = singleBicycle.getTotal();
                        page = (Double.valueOf(Math.ceil(total / 1000))).intValue();
                        for (int i = 1; i <= page; i++) {
                            try {
                                Thread.sleep(500);
                                GetAllBicycle(v1, v2, String.valueOf(i));
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                sweetAlertDialog.dismiss();
                               /* Toast.makeText(MainActivity.this, "" + singleBicycle.getMessage(), Toast.LENGTH_LONG).show();*/
                            }
                        });
                    }
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sweetAlertDialog.dismiss();
                            Toast.makeText(MainActivity.this, "数据异常，请重试", Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        });
    }

    /*获取500单车数量 */
    public void GetAllBicycle(double v1, double v2, String pagex) {

        String x = "" + v1 + "," + v2;
        OkHttpClient mOkHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(Url + "?ak=IK5AlGXoZ23tDAGjldRalicbhdpsrKwE&service_id=135958&center=" + x + "&radius=500&page_size=1000&coord_type_output=gcj02&coord_type_input=gcj02&page_index=" + pagex)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                time++;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "网络异常，请检查网络连接", Toast.LENGTH_LONG).show();
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String resp = response.body().string();
                Log.i("15641511", resp);
                final SingleBicycle singleBicycle = GsonTools.changeGsonToBean(resp, SingleBicycle.class);
                time++;
                if (singleBicycle != null) {
                    if (singleBicycle.getStatus() == 0) {
                        int size = singleBicycle.getEntities().size();
                        for (int i = 0; i < size; i++) {
                            if (isDestroy) {
                                //已经销毁地图了，退出循环
                                return;
                            }
                            if (singleBicycle.getEntities().get(i).getStatus() == null) {
                                singleBicycle.getEntities().get(i).setStatus("0");
                            }
                            double latitude = singleBicycle.getEntities().get(i).getLatest_location().getLatitude();
                            double longitude = singleBicycle.getEntities().get(i).getLatest_location().getLongitude();
                            LatLng latLng = new LatLng(latitude, longitude);
                            MultiPointItem multiPointItem = new MultiPointItem(latLng);
                            multiPointItem.setObject(singleBicycle.getEntities().get(i));
                            String status = singleBicycle.getEntities().get(i).getStatus();

                            switch (status) {
                                case "0"://正常车
                                    list0.add(multiPointItem);
                                    break;
                                case "1"://使用中
                                    list1.add(multiPointItem);
                                    break;
                                case "2"://离线
                                    list2.add(multiPointItem);
                                    break;
                                case "3"://报废
                                    list3.add(multiPointItem);
                                    break;
                                case "7"://故障
                                    list7.add(multiPointItem);
                                    break;
                                case "8"://低电量
                                    list8.add(multiPointItem);
                                    break;
                                case "9"://僵尸
                                    list9.add(multiPointItem);
                                    break;
                                case "10"://不可充电
                                    list6.add(multiPointItem);
                                    break;
                                case "11"://维修中
                                    list4.add(multiPointItem);
                                    break;
                                case "12"://未绑定
                                    list5.add(multiPointItem);
                                    break;
                                case "13"://电子围栏外
                                    list14.add(multiPointItem);
                                    break;
                                case "14"://用户上报的故障车
                                    list15.add(multiPointItem);
                                    break;
                                case "15"://需要召回的车辆
                                    list16.add(multiPointItem);
                                    break;
                                case "16"://关机车
                                    list17.add(multiPointItem);
                                    break;

                                default:
                                    break;
                            }
                        }
                        if (time == page) {
                            Message message = handler.obtainMessage();
                            message.what = 1;
                            handler.sendMessage(message);
                        }
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                              /*  Toast.makeText(MainActivity.this, "" + singleBicycle.getMessage(), Toast.LENGTH_LONG).show();*/
                            }
                        });
                    }

                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "数据异常，请重试", Toast.LENGTH_LONG).show();
                        }
                    });
                }

            }
        });
    }

    /*获取500米 停放点*/
    public void IsOverAreaPoint(final double v1, final double v2) {
        timep = 0;
        String x = "" + v1 + "," + v2;
        OkHttpClient mOkHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(Url + "?ak=IK5AlGXoZ23tDAGjldRalicbhdpsrKwE&service_id=140284&center=" + x + "&radius=500&page_size=1&coord_type_input=gcj02")
                .build();

        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        sweetAlertDialog.dismiss();
                        Toast.makeText(MainActivity.this, "网络异常，请检查网络连接", Toast.LENGTH_LONG).show();
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String resp = response.body().string();
                Log.i("15641512", resp);
                final StationInfo stationInfo = GsonTools.changeGsonToBean(resp, StationInfo.class);
                if (stationInfo != null) {
                    if (stationInfo.getStatus() == 0) {
                        double total = stationInfo.getTotal();
                        pagep = (Double.valueOf(Math.ceil(total / 1000))).intValue();
                        for (int i = 1; i <= pagep; i++) {
                            try {
                                Thread.sleep(500);
                                GetAllPoint(v1, v2, String.valueOf(i));
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                sweetAlertDialog.dismiss();
                               /* Toast.makeText(MainActivity.this, "" + stationInfo.getMessage(), Toast.LENGTH_LONG).show();*/
                            }
                        });
                    }
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sweetAlertDialog.dismiss();
                            Toast.makeText(MainActivity.this, "数据异常，请重试", Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        });
    }

    /*获取500米所有停放点*/
    public void GetAllPoint(double v1, double v2, String pagex) {
        String x = "" + v1 + "," + v2;
        OkHttpClient mOkHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(Url + "?ak=IK5AlGXoZ23tDAGjldRalicbhdpsrKwE&service_id=140284&center=" + x + "&radius=500&page_size=1000&coord_type_output=gcj02&coord_type_input=gcj02&page_index=" + pagex)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                timep++;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "网络异常，请检查网络连接", Toast.LENGTH_LONG).show();
                    }
                });

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String resp = response.body().string();
                Log.i("15641511", resp);
                final StationInfo stationInfo = GsonTools.changeGsonToBean(resp, StationInfo.class);
                timep++;
                if (stationInfo != null) {
                    if (stationInfo.getStatus() == 0) {
                        int size = stationInfo.getEntities().size();
                        for (int i = 0; i < size; i++) {
                            if (isDestroy) {
                                //已经销毁地图了，退出循环
                                return;
                            }
                            double latitude = stationInfo.getEntities().get(i).getLatest_location().getLatitude();
                            double longitude = stationInfo.getEntities().get(i).getLatest_location().getLongitude();
                            LatLng latLng = new LatLng(latitude, longitude);
                            MultiPointItem multiPointItem = new MultiPointItem(latLng);
                            multiPointItem.setObject(stationInfo.getEntities().get(i));
                            String status = stationInfo.getEntities().get(i).getChildrenAreaType();
                            switch (status) {

                                case "1"://普通
                                    list10.add(multiPointItem);
                                    break;
                                case "3"://一期
                                    list11.add(multiPointItem);
                                    break;
                                case "4"://重点
                                    list12.add(multiPointItem);
                                    break;
                                case "5"://已投放
                                    list13.add(multiPointItem);
                                    break;
                                case "6"://维修点
                                    list18.add(multiPointItem);
                                    break;
                                case "7"://中转点
                                    list19.add(multiPointItem);
                                    break;
                                default:
                                    break;
                            }
                        }
                        if (timep == pagep) {
                            Message message = handler.obtainMessage();
                            message.what = 2;
                            handler.sendMessage(message);
                        }
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                /*Toast.makeText(MainActivity.this, "" + stationInfo.getMessage(), Toast.LENGTH_LONG).show();*/
                            }
                        });
                    }

                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "数据异常，请重试", Toast.LENGTH_LONG).show();
                        }
                    });
                }

            }
        });
    }

    /*上传点位数量*/
    public void uploadNumber(String id, String number, String flag) {
        final OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("action", "UPLOADPARKINGNUM")
                .add("adminId", String.valueOf(SharedPreferencesUtils.getParam(MainActivity.this, "adminId", "")))
                .add("locatingStopId", id)
                .add("peakParkingNum", number)
                .add("timeFlag", flag)
                .build();

        final Request request = new Request.Builder()
                .url("http://operate.99bicycle.com/OperateBicyclePro/operationperson?")
                .post(formBody)
                .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Log.i("456921", string);
                        final ReLogout mse = GsonTools.changeGsonToBean(string, ReLogout.class);
                        if (mse != null) {
                            if (mse.getCode() == 1) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(MainActivity.this, "" + mse.getMessage(), Toast.LENGTH_LONG).show();
                                        sweetAlertDialog.dismiss();
                                    }
                                });
                            } else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(MainActivity.this, "" + mse.getMessage(), Toast.LENGTH_LONG).show();
                                        sweetAlertDialog.dismiss();
                                    }
                                });
                            }
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, "数据异常  请重试", Toast.LENGTH_LONG).show();
                                    sweetAlertDialog.dismiss();
                                }
                            });
                        }
                    } else {
                        throw new IOException("Unexpected code " + response);
                    }
                } catch (IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "网络异常  请重试", Toast.LENGTH_LONG).show();
                            sweetAlertDialog.dismiss();
                        }
                    });
                    e.printStackTrace();
                }
            }
        }).start();


    }

    /*删除点位*/
    public void deletePoint(String id, final SweetAlertDialog s) {
        Log.i("3378", String.valueOf(SharedPreferencesUtils.getParam(MainActivity.this, "adminId", "")));
        final OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("action", "DELLOCATINGINFO")
                .add("adminId", String.valueOf(SharedPreferencesUtils.getParam(MainActivity.this, "adminId", "")))
                .add("id", id)
                .build();

        final Request request = new Request.Builder()
                .url("http://operate.99bicycle.com/OperateBicyclePro/operationperson?")
                .post(formBody)
                .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Log.i("456921", string);
                        final ReLogout mse = GsonTools.changeGsonToBean(string, ReLogout.class);
                        if (mse != null) {
                            if (mse.getCode() == 1) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        s.setTitleText("删除成功")
                                                .setContentText("" + mse.getMessage())
                                                .setConfirmText("确定")
                                                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                                    @Override
                                                    public void onClick(SweetAlertDialog sweetAlertDialogx) {
                                                        sweetAlertDialogx.dismiss();
                                                        Log.i("212545","1");
                                                        reloadMap();
                                                        sweetAlertDialog.show();
                                                        IsOverArea(ciclat, ciclon);
                                                        IsOverAreaPoint(ciclat, ciclon);
                                                    }
                                                })
                                                .changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
                                    }
                                });
                            } else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        s.setTitleText("删除失败")
                                                .setContentText("" + mse.getMessage())
                                                .setConfirmText("确定")
                                                .setConfirmClickListener(null)
                                                .changeAlertType(SweetAlertDialog.WARNING_TYPE);
                                    }
                                });
                            }
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, "数据异常  请重试", Toast.LENGTH_LONG).show();
                                    sweetAlertDialog.dismiss();
                                }
                            });
                        }

                    } else {
                        throw new IOException("Unexpected code " + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }

    /*绘制多边形*/
    public void setPolygon() {
        if (latLngs.isEmpty()) {
            return;
        }
        // 声明 多边形参数对象
        PolygonOptions polygonOptions = new PolygonOptions();
        polygonOptions.addAll(latLngs);
        polygonOptions.strokeWidth(15)
                .strokeColor(Color.argb(200, 250, 20, 60))
                .fillColor(Color.argb(0, 0, 0, 0));   // 多边形的填充色
        yuanshipolygon = getMap().addPolygon(polygonOptions);

    }

    /*绘制圆形*/
    public void setClc(double lat, double lon) {
        LatLng latLng = new LatLng(lat, lon);
        circle = getMap().addCircle(new CircleOptions().center(latLng).radius(500).fillColor(Color.argb(0, 1, 1, 1)).strokeColor(Color.argb(150, 76, 180, 255)).strokeWidth(5));
    }

    /*获取城市代码对应城市名*/
    public void getCityName() {
        Log.i("3378", String.valueOf(SharedPreferencesUtils.getParam(MainActivity.this, "adminId", "")));
        final OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("action", "GETDELIVERCITY")
                .add("adminId", String.valueOf(SharedPreferencesUtils.getParam(MainActivity.this, "adminId", "")))
                .build();

        final Request request = new Request.Builder()
                .url("http://operate.99bicycle.com/OperateBicyclePro/administrator?")
                .post(formBody)
                .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        SharedPreferencesUtils.setParam(MainActivity.this, "cityname", string);
                        Log.i("21214", string);
                    } else {
                        throw new Exception("Unexpected code " + response);
                    }
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                        }
                    });
                    e.printStackTrace();
                }
            }
        }).start();


    }


    @Override
    protected void onPause() {
        super.onPause();
        map.onPause();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppManager.getAppManager().finishActivity(this);
        stopService(new Intent(MainActivity.this, UploadLocation.class));
        map.onDestroy();
        isDestroy = true;
        mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
        mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
    }

    @Override
    protected void onResume() {
        super.onResume();
        map.onResume();

    }

    @Override
    protected void onStart() {

        super.onStart();
    }

    @Override
    protected void onStop() {

        super.onStop();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        map.onSaveInstanceState(outState);
    }


    @Override
    public void onBackPressed() {
        exit();
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            new Timer().schedule(new TimerTask() {

                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
        } else {
            finish();
        }
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(60);
    }

    @Override
    public void onChange(AnimCheckBox animCheckBox, boolean b) {
        switch (animCheckBox.getId()) {


            case R.id.checkbox1://正常车

                if (checkBox1.isChecked()) {
                    carall = carall + car0;
                    multiPointOverlay0.setEnable(true);
                } else {
                    carall = carall - car0;
                    multiPointOverlay0.setEnable(false);
                }
                break;
            case R.id.checkbox2://未绑定

                if (checkBox2.isChecked()) {
                    carall = carall + car5;
                    multiPointOverlay5.setEnable(true);
                } else {
                    carall = carall - car5;
                    multiPointOverlay5.setEnable(false);
                }
                break;
            case R.id.checkbox3://使用中

                if (checkBox3.isChecked()) {
                    carall = carall + car1;
                    multiPointOverlay1.setEnable(true);
                } else {
                    carall = carall - car1;
                    multiPointOverlay1.setEnable(false);
                }
                break;
            case R.id.checkbox4://维修

                if (checkBox4.isChecked()) {
                    carall = carall + car4;
                    multiPointOverlay4.setEnable(true);
                } else {
                    carall = carall - car4;
                    multiPointOverlay4.setEnable(false);
                }
                break;
            case R.id.checkbox5://离线

                if (checkBox5.isChecked()) {
                    carall = carall + car2;
                    multiPointOverlay2.setEnable(true);
                } else {
                    carall = carall - car2;
                    multiPointOverlay2.setEnable(false);
                }
                break;
            case R.id.checkbox6://不可充电

                if (checkBox6.isChecked()) {
                    carall = carall + car6;
                    multiPointOverlay6.setEnable(true);
                } else {
                    carall = carall - car6;
                    multiPointOverlay6.setEnable(false);
                }
                break;
            case R.id.checkbox7://故障

                if (checkBox7.isChecked()) {
                    carall = carall + car7;
                    multiPointOverlay7.setEnable(true);
                } else {
                    carall = carall - car7;
                    multiPointOverlay7.setEnable(false);
                }
                break;
            case R.id.checkbox8://报废

                if (checkBox8.isChecked()) {
                    carall = carall + car3;
                    multiPointOverlay3.setEnable(true);
                } else {
                    carall = carall - car3;
                    multiPointOverlay3.setEnable(false);
                }
                break;
            case R.id.checkbox9://低电

                if (checkBox9.isChecked()) {
                    carall = carall + car8;
                    multiPointOverlay8.setEnable(true);
                } else {
                    carall = carall - car8;
                    multiPointOverlay8.setEnable(false);
                }
                break;
            case R.id.checkbox10://僵尸

                if (checkBox10.isChecked()) {
                    carall = carall + car9;
                    multiPointOverlay9.setEnable(true);
                } else {
                    carall = carall - car9;
                    multiPointOverlay9.setEnable(false);
                }
                break;
            case R.id.checkbox11://普通

                if (checkBox11.isChecked()) {
                    pointall = pointall + car10;
                    multiPointOverlay10.setEnable(true);
                } else {
                    pointall = pointall - car10;
                    multiPointOverlay10.setEnable(false);
                }
                break;
            case R.id.checkbox12://一期
                if (checkBox12.isChecked()) {
                    pointall = pointall + car11;
                    multiPointOverlay11.setEnable(true);
                } else {
                    pointall = pointall - car11;
                    multiPointOverlay11.setEnable(false);
                }
                break;
            case R.id.checkbox13://重点

                if (checkBox13.isChecked()) {
                    pointall = pointall + car12;
                    multiPointOverlay12.setEnable(true);
                } else {
                    pointall = pointall - car12;
                    multiPointOverlay12.setEnable(false);
                }
                break;
            case R.id.checkbox14://已投放


                if (checkBox14.isChecked()) {
                    pointall = pointall + car13;
                    multiPointOverlay13.setEnable(true);
                } else {
                    pointall = pointall - car13;
                    multiPointOverlay13.setEnable(false);
                }
                break;
            case R.id.checkbox15://围栏外

                if (checkBox15.isChecked()) {
                    carall = carall + car14;
                    multiPointOverlay14.setEnable(true);
                } else {
                    carall = carall - car14;
                    multiPointOverlay14.setEnable(false);
                }
                break;
            case R.id.checkbox16://用户报障

                if (checkBox16.isChecked()) {
                    carall = carall + car15;
                    multiPointOverlay15.setEnable(true);
                } else {
                    carall = carall - car15;
                    multiPointOverlay15.setEnable(false);
                }
                break;

            case R.id.checkbox17://需召回

                if (checkBox17.isChecked()) {
                    carall = carall + car16;
                    multiPointOverlay16.setEnable(true);
                } else {
                    carall = carall - car16;
                    multiPointOverlay16.setEnable(false);
                }
                break;
            case R.id.checkbox18://关机

                if (checkBox18.isChecked()) {
                    carall = carall + car17;
                    multiPointOverlay17.setEnable(true);
                } else {
                    carall = carall - car17;
                    multiPointOverlay17.setEnable(false);
                }
                break;
            case R.id.checkbox19://维修点

                if (checkBox19.isChecked()) {
                    carall = carall + car18;
                    multiPointOverlay18.setEnable(true);
                } else {
                    carall = carall - car18;
                    multiPointOverlay18.setEnable(false);
                }
                break;
            case R.id.checkbox20://中转点

                if (checkBox20.isChecked()) {
                    carall = carall + car19;
                    multiPointOverlay19.setEnable(true);
                } else {
                    carall = carall - car19;
                    multiPointOverlay19.setEnable(false);
                }
                break;
            default:
                break;

        }
        String all = String.valueOf(carall);
        carNumber.setText(all);
        String poiall = String.valueOf(pointall);
        locationNumber.setText(poiall);
        daynumber.setText("");
        nightnumber.setText("");
    }


    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    //移动APP调起Android高德地图方式
    private void startGaoDeMap(String latitude, String longitude, String type) {
        Intent intent = new Intent("android.intent.action.VIEW",
                android.net.Uri.parse("androidamap://route?sourceApplication=softname&sname=" + "我的位置" + "&dlat=" + latitude + "&dlon=" + longitude + "&dev=0&t=" + type));
        intent.setPackage("com.autonavi.minimap");

        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        if (isInstallByread("com.autonavi.minimap")) {
            startActivity(intent);
        } else {
            Toast.makeText(MainActivity.this, "请先安装高德地图客户端", Toast.LENGTH_SHORT).show();
        }
    }

    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName)
                .exists();
    }

}
